﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using S9Engine;
using System.Text.RegularExpressions;

public partial class Search : Parser
{
    private string _search;
    private int _page;
    private int _pageSize;
    private string _manufactory;    

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            _parser.SetCurrentDir("~/tpl");
            _parser.SetLanguageFile("~/templates/language.txt", _currentLanguage);

            Session["CurrentPage"] = "Search.aspx";

            string page = GetRequest("page");
            if (!string.IsNullOrEmpty(page)) _page = int.Parse(page);
            _search = GetRequest("txtSearch");            
            _pageSize = int.Parse(_parser.GetConfig("RowsPerPage", "10"));

            LoadFile("search.html", false);

            if (string.IsNullOrEmpty(_search))
            {
                _parser.Parse("Main.NoResult");
                return;
            }
            SearchAll();
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
        finally
        {
            _parser.Parse("Main");
            _parser.Out("Main");
        }
    }

    private void SearchAll()
    {
        double price = 0;
        _search = _search.ToLower().TrimEnd().TrimStart();
        double.TryParse(_search, out price);

        //string fromPrice = GetRequest("fromPrice", "0");
        //string toPrice = GetRequest("toPrice", "0");
        //string searchCategory = GetRequest("searchCategory", "0");

        //_parser.Assign("searchedCategory", searchCategory);

        var totalResult = LoadAllProduct("Code", false, false, 0).ToList();
        if (null != _search && _search.ToLower()!="tìm kiếm") totalResult = totalResult.Where(t => t.Name.ToLower().Contains(_search) || t.Excerpt.ToLower().Contains(_search) || t.Content.ToLower().Contains(_search) || t.Manufactory.ToLower().Contains(_search) || t.Meta.Select(m => m.Key, m => m.Value, "Code").ToLower().Contains(_search)).ToList();
        //if ("0" != searchCategory) totalResult = totalResult.Where(t => t.Parent.Equals(long.Parse(searchCategory))).ToList();
        //double fPrice = (fromPrice=="") ? 0 : double.Parse(fromPrice.Replace(",", ""));
        //double tPrice = (toPrice == "") ? 0 : double.Parse(toPrice.Replace(",", ""));

        //if (fPrice != 0) { totalResult = totalResult.Where(t => (t.Price >= fPrice) || (double.Parse(t.Meta.Select(m => m.Key, m => m.Value, "SalePrice")) >= fPrice)).DistinctBy(t => t.ID).ToList(); }
        //if (tPrice != 0 && tPrice > fPrice) {
        //    totalResult = totalResult.Where(t => (t.Price >= fPrice && t.Price <= tPrice) || (double.Parse(t.Meta.Select(m => m.Key, m => m.Value, "SalePrice")) <= tPrice && double.Parse(t.Meta.Select(m => m.Key, m => m.Value, "SalePrice")) >= fPrice)).DistinctBy(t => t.ID).ToList();
        //}
        //if (fPrice < tPrice){
        //    totalResult = totalResult.Where(t => (t.Price >= fPrice && t.Price <= tPrice) || (double.Parse(t.Meta.Select(m => m.Key, m => m.Value, "SalePrice")) <= tPrice && double.Parse(t.Meta.Select(m => m.Key, m => m.Value, "SalePrice")) >= fPrice)).DistinctBy(t => t.ID).ToList();
        //}
        //else {
        //    //if (fPrice != 0) totalResult = totalResult.Where(t => (t.Price >= fPrice) || (double.Parse(t.Meta.Select(m => m.Key, m => m.Value, "SalePrice")) >= fPrice)).DistinctBy(t => t.ID).ToList();
        //}

        //if (fPrice < tPrice) { totalResult = totalResult.Where(t => (t.Price >= fPrice && t.Price <= tPrice) || (double.Parse(t.Meta.Select(m => m.Key, m => m.Value, "SalePrice")) <= tPrice && double.Parse(t.Meta.Select(m => m.Key, m => m.Value, "SalePrice")) >= fPrice)).DistinctBy(t => t.ID).ToList();}
        //else {
        //    if (fPrice != 0) { totalResult = totalResult.Where(t => (t.Price >= fPrice) || (double.Parse(t.Meta.Select(m => m.Key, m => m.Value, "SalePrice")) >= fPrice)).DistinctBy(t => t.ID).ToList();}
        //    if (tPrice != 0) { totalResult = totalResult.Where(t => (t.Price <= tPrice) || (double.Parse(t.Meta.Select(m => m.Key, m => m.Value, "SalePrice")) <= tPrice)).DistinctBy(t => t.ID).ToList();}
        //}
        _parser.Assign("searchedValue", _search);
        //_parser.Assign("fromPrice", fPrice.ToString());
        //_parser.Assign("toPrice", tPrice.ToString());
        
        if (totalResult.Count == 0)
        {
            _parser.Parse("Main.NoResult");
        }
        else
        {
            double totalRecord = totalResult.Count();
            int page = int.Parse(Request["page"] ?? "1");

            int totalPage = (int)(totalRecord / _pageSize);

            if (totalPage * _pageSize < totalRecord) totalPage++;

            if (totalRecord != 0)
            {
                int startRecord = (page == 1 ? 0 : ((page - 1) * _pageSize));
                int endRecord = (int)(page * _pageSize > totalRecord ? totalRecord : page * _pageSize);
                                
                for (int i = startRecord; i < endRecord; i++)
                {
                    //string salePrice = double.Parse(totalResult[i].Meta.Select(m => m.Key, m => m.Value, "SalePrice")).ToString("N0").Replace(',','.');
                    string code = totalResult[i].Meta.Select(m => m.Key, m => m.Value, "Code");                                        
                                        
                    _parser.Assign("productID", totalResult[i].ID.ToString());
                    _parser.Assign("categoryID", totalResult[i].Parent.ToString());
                    _parser.Assign("productName", totalResult[i].Name);
                    _parser.Assign("productImage", totalResult[i].Image);                                                            
                    _parser.Assign("productCode", totalResult[i].Meta.Select(m => m.Key, m => m.Value, "Code"));

                    //string productNew = totalResult[i].Meta.Select(m => m.Key, m => m.Value, "New");
                    //if (productNew.ToLower() == "true"){
                    //    _parser.Parse(string.Format("Main.ProductList.ProductListItem.NewProduct"));
                    //}
                    //<img src="../assets/images/icon_new.gif" alt="Sản phẩm mới">                    
                    //if (double.Parse(totalResult[i].Meta.Select(m => m.Key, m => m.Value, "SalePrice")) < totalResult[i].Price && 0 != double.Parse(totalResult[i].Meta.Select(m => m.Key, m => m.Value, "SalePrice"))){
                    //    _parser.Assign("productPrice", totalResult[i].Price.ToString("N0").Replace(',', '.'));
                    //    _parser.Assign("productSalePrice", double.Parse(totalResult[i].Meta.Select(m => m.Key, m => m.Value, "SalePrice")).ToString("N0").Replace(',', '.'));

                    //    _parser.Parse(string.Format("Main.ProductList.ProductListItem.SalePrice"));
                    //}
                    //else{
                    //    _parser.Assign("productPrice", string.IsNullOrEmpty(totalResult[i].Price.ToString()) ? "Liên hệ" : totalResult[i].Price.ToString("N0").Replace(',', '.') + " VNĐ");
                    //    _parser.Parse(string.Format("Main.ProductList.ProductListItem.Price"));
                    //}                   
                    
                    _parser.Parse("Main.ProductList.ProductListItem");
                }

                _parser.Assign("totalPage", totalPage.ToString());
                _parser.Assign("totalRecord", totalRecord.ToString());
                _parser.Assign("currentPage", page.ToString());

                if (totalPage != 1)
                {
                    int pagingPage = page / 6;
                    int startPage = 1;
                    int endPage = 1;

                    if (page % 6 == (6 - 1) && page > 6)
                    {
                        startPage = page;
                    }
                    else
                    {
                        startPage = (pagingPage * 6 == 0 ? 1 : pagingPage * 6);
                    }

                    endPage = (startPage + (6 - 1) > totalPage ? totalPage : startPage + (6 - 1));

                    _parser.Assign("pageIndexPrevious", (page == 1 ? 1 : page - 1).ToString());
                    _parser.Assign("pageIndexNext", (page == totalPage ? totalPage : page + 1).ToString());

                    for (int i = startPage; i <= endPage; i++)
                    {
                        _parser.Assign("current", page == i ? " class=\"current\"" : string.Empty);
                        _parser.Assign("pageIndex", i.ToString());
                        _parser.Parse("Main.ProductList.Paging.PagingItem");
                    }

                    _parser.Parse("Main.ProductList.Paging.PagingPrevious");
                    _parser.Parse("Main.ProductList.Paging.PagingNext");
                    _parser.Parse("Main.ProductList.Paging");
                }

                _parser.Parse("Main.ProductList");
            }
        }

        totalResult = null;
    }    
}